package service;

import bean.Bicycle;
import bean.User;
import dao.BicycleDAO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.JsonWrapper;
import util.JsonWrapperBuilder;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Optional;

/**
 * @author liu
 */
public class BicycleService {

    private BicycleDAO bicycleDAO;

    public BicycleService() {
        bicycleDAO = new BicycleDAO();
    }

    public JSONObject bikesPagination(int start, int pagesize) {
        List<Bicycle> bicycleList = bicycleDAO.getPage((start - 1) * pagesize, pagesize);
        JSONArray bicycleArray = new JSONArray();
        for (int i = 0; i < bicycleList.size(); i++) {
            JSONObject a = getOneBikeJson(bicycleList.get(i));
            bicycleArray.add(a);
        }
        return new JsonWrapperBuilder()
            .setStatus(200)
            .setMsg("success")
            .setDataJsonArray("values", bicycleArray)
            .build();
    }

    private JSONObject getOneBikeJson(Bicycle bicycle) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JsonWrapper value = new JsonWrapper();
        value.setEntry("id", bicycle.getBicycleid());
        if (bicycle.getUserName() == null) {
            value.setEntry("from", "公司内购");
        } else {
            value.setEntry("from", bicycle.getUserName());
        }
        value.setEntry("time", sdf.format(bicycle.getTime()));
        value.setEntry("photo", bicycle.getPhotourl());
        value.setEntry("lockId", bicycle.getLockid());
        JsonWrapper location = new JsonWrapper();
        location.setEntry("x", bicycle.getLocationx());
        location.setEntry("y", bicycle.getLocationx());
        value.setEntry("status", bicycle.getStatus());
        value.setEntry("energy", bicycle.getEnergy());
        value.getNoData().put("location", location.getNoData());
        return value.getNoData();
    }

    public JSONObject bikesQuery(String type, String value) {
        Bicycle bicycle = null;
        if ("id".equals(type)) {
            bicycle = bicycleDAO.selectById(Integer.parseInt(value));
        } else if ("lockId".equals(type)) {
            bicycle = bicycleDAO.selectByLockId(Integer.parseInt(value));
        }
        if (bicycle.getBicycleid() != null) {
            return new JsonWrapperBuilder()
                .setStatus(200)
                .setMsg("success")
                .setDataJsonObject("value", getOneBikeJson(bicycle))
                .build();
        } else {
            return new JsonWrapperBuilder()
                .setStatus(304)
                .setMsg("failed").build();
        }
    }

    public JSONObject bikeDynamicQuery(String type, String prefix) {
        List<Integer> idList = null;
        if ("id".equals(type)) {
            idList = bicycleDAO.selectByIdPrefix(prefix);
        } else if ("lockId".equals(type)) {
            idList = bicycleDAO.selectByLockIdPrefix(prefix);
        }
        JSONArray values = new JSONArray();
        for (int i = 0; i < idList.size(); i++) {
            JsonWrapper value = new JsonWrapper();
            value.setEntry("value", idList.get(i));
            value.setParent(values);
        }
        return new JsonWrapperBuilder()
            .setStatus(200)
            .setMsg("success")
            .setDataJsonArray("values", values)
            .build();
    }

    public JSONObject bikeTotal() {
        int total = bicycleDAO.getTotal();
        return new JsonWrapperBuilder()
            .setStatus(200)
            .setMsg("success")
            .setDataEntry("total", total).build();
    }

    public void addBicycle(int userId, String lockId, String imageName, int status) {

        Bicycle bicycle = new Bicycle();

        bicycle.setLockid(Integer.parseInt(lockId));
        bicycle.setFrom(userId);
        bicycle.setEnergy(100f);
        bicycle.setStatus(status);
        bicycle.setPhotourl(imageName);
        bicycleDAO.addBicycle(bicycle);
    }

    public boolean delete(String id) {
        return (bicycleDAO.deleteById(Integer.parseInt(id)) > 0);
    }

    public boolean updateById(Integer id, Integer lockId, Integer status) {
        return (bicycleDAO.updateByIdSelective(id, lockId, status) > 0);
    }

    public int getUserId(String username) {
        return bicycleDAO.getUserId(username);
    }

    public int addUser(User user) {
        int userId = -1;
        try {
            userId = bicycleDAO.userAdd(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userId;
    }

    public JSONObject bikeNearby(String myLocationX, String myLocationY) {
        double myLat = Double.parseDouble(myLocationX);
        double myLng = Double.parseDouble(myLocationY);
        double range = 180 / Math.PI * 1 / 6372.797;     //里面的 1 就代表搜索 1km 之内，单位km
        double lngR = range / Math.cos(myLat * Math.PI / 180.0);
        double maxLat = myLat + range;
        double minLat = myLat - range;
        double maxLng = myLng + lngR;
        double minLng = myLng - lngR;
        List<Bicycle> bicycleList = bicycleDAO.getNearbyBike(maxLat, minLat, maxLng, minLng);
        JSONArray bicycleArray = new JSONArray();
        for (int i = 0; i < bicycleList.size(); i++) {
            JsonWrapper value = new JsonWrapper();
            value.setEntry("bicycleId", bicycleList.get(i).getBicycleid());
            value.setEntry("locationX", bicycleList.get(i).getLocationx());
            value.setEntry("locationY", bicycleList.get(i).getLocationy());
            value.setEntry("status", bicycleList.get(i).getStatus());
            bicycleArray.add(value.getNoData());
        }
        return new JsonWrapperBuilder()
            .setStatus(200)
            .setMsg("success")
            .setDataJsonArray("bikes", bicycleArray)
            .build();
    }

    public boolean isLockValid(String lockId) throws SQLException {
        Optional<Bicycle> bicycle = bicycleDAO.findBycicleById(lockId);
        return !bicycle.isPresent();
    }
}
